package server

import (
	"net"
	"strconv"
	"time"
)

//客户端连接，一个连接一个TcpConn
type TcpConn struct {
	Id       string   //客户端唯一标识
	Connect  net.Conn //客户端连接对象
	Server   *SocketServer
	LastTime int64 //最后通讯时间
}

//创建连接客户端
func MakeClient(connnect net.Conn, server *SocketServer) *TcpConn {
	client := &TcpConn{
		Id:       connnect.RemoteAddr().String(),
		Connect:  connnect,
		Server:   server,
		LastTime: time.Now().Unix(),
	}
	return client
}

//接收数据
func (conn *TcpConn) HandleMessage() {
	var buffer [1024]byte //测试用8，真实环境用多少一点
	msg := ""
	for {
		readcount, err := conn.Connect.Read(buffer[:])
		if err != nil {
			conn.Server.RemoveClient(conn)
			conn.Server.OnError("读取数据错误，关闭连接:", err)
			break
		}
		if readcount == 0 {
			conn.Server.OnError("读取数据失败:"+strconv.Itoa(readcount), nil)
			continue
		}
		conn.LastTime = time.Now().Unix()
		msg = string(buffer[:readcount])
		conn.Server.OnMessage(conn, msg)
	}
}
